/* eslint valid-jsdoc: "off" */

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */

// 导入数据库配置文件
const dbConfig = require('./database.js');
const path = require('path');
const fs = require('fs');

// 根据环境选择数据库配置
const env = process.env.NODE_ENV || 'development';
const currentDbConfig = dbConfig[env];

module.exports = appInfo => {
  // 确保上传目录存在
  const uploadConfig = {
    basePath: 'app/public/uploads',
    enableDateDir: true,
  };
  const baseUploadPath = path.join(appInfo.baseDir, uploadConfig.basePath);
  if (!fs.existsSync(baseUploadPath)) {
    fs.mkdirSync(baseUploadPath, { recursive: true });
  }
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1754970419869_6115';

  // add your middleware config here
  config.middleware = ['response', 'errorHandler'];

  // 配置MySQL数据库
  config.sequelize = {
    dialect: 'mysql',
    host: currentDbConfig.host,
    port: 3306,
    database: currentDbConfig.database,
    username: currentDbConfig.username,
    password: currentDbConfig.password,
    define: {
      // 表名不区分大小写（使用小写）
      freezeTableName: true,
      // 自动添加时间戳
      timestamps: true,
      // 时间戳字段名
      createdAt: 'create_time',
      updatedAt: 'update_time',
      // 使用下划线命名
      underscored: true,
      // 添加字段备注
      comment: true,
    },
  };

  // 安全配置
  config.security = {
    csrf: {
      enable: false, // 禁用CSRF验证，适用于API接口
    },
    xframe: {
      enable: false,
    },
  };

  config.logger = {
    level: 'ERROR', // 提高日志级别，减少输出
    file: false, // 禁用文件日志
    consoleLevel: 'ERROR',
    disableConsoleAfterReady: false,
  };

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
    // JWT配置
    jwt: {
      secret: '_1754970419869_6115', // 请更换为安全的密钥
      expiresIn: '24h', // 默认过期时间
    },
    // 图片上传配置
    upload: {
      // 图片上传基础路径，可配置为绝对路径或相对路径
      basePath: 'public/uploads',
      // 是否按日期(年/月)分文件夹存储
      enableDateDir: true,
      // 图片URL前缀
      imageUrlPrefix: '/staticImage',
    },
    // multipart配置
    multipart: {
      mode: 'file',
      tmpdir: path.join(appInfo.baseDir, 'tmp'),
      cleanSchedule: {
        cron: '0 30 4 * * *', // 每天凌晨4:30清理临时文件
      },
      fileSize: '5mb',
      fileExtensions: [
        '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp',
        '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm',
        '.mp3', '.wav', '.flac', '.aac', '.ogg',
        '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
        '.txt', '.zip', '.rar', '.7z', '.tar', '.gz',
      ],
      whitelist: () => true, // 允许所有文件类型
      limits: {
        fileSize: 5 * 1024 * 1024, // 5MB
      },
    },
  };

  return {
    ...config,
    ...userConfig,
  };
};
